import { registerMapItem, type MapItemGroup, addMapItemInfoView, type MapItem } from '@/map-item'
import { entityMapItem, entityMapItemType } from '../base'
import type { Routing } from '../routing'
import type { Aircraft } from '../aircraft'
import { type Airport } from '../airport'
import type { FlightPlan } from './types'
import { flightPlanByRouting } from './fpl-index'
import { highlightFlightPlanFeatures } from './feature'
import FlightPlanInfoVue from './FlightPlanInfo.vue'
import AircraftFlightPlanList from './AircraftFlightPlanList.vue'
import AirportFlightPlanInfoVue from './AirportFlightPlanInfo.vue'

function search(
  lng: number,
  lat: number,
  radius: number,
  result: Record<string, MapItemGroup<any>>
): Set<FlightPlan> | null {
  const routings = result[entityMapItemType('Routing')] as MapItemGroup<Routing>
  if (!routings) {
    return null
  }
  let set: Set<FlightPlan> | null = null
  for (const r of routings.items) {
    const fpls = flightPlanByRouting.get(r.id)
    if (!fpls || fpls.size === 0) {
      continue
    }
    if (!set) {
      set = new Set()
    }
    for (const f of fpls) {
      set.add(f)
    }
  }
  return set
}

export function initFlightPlanMapItems() {
  registerMapItem({
    type: entityMapItemType('FlightPlan'),
    typeName: '飞行计划',
    icon: 'mas-icon-FlightPlan',
    getName: (f) => f.id,
    index: {
      enable: () => true,
      search
    },
    highlight: highlightFlightPlanFeatures,
    infoView: FlightPlanInfoVue
  })
  addMapItemInfoView<Aircraft>(entityMapItemType('Aircraft'), AircraftFlightPlanList)
  addMapItemInfoView<Airport>(entityMapItemType('Airport'), AirportFlightPlanInfoVue)
}

export function flightPlanMapItem(id: string): MapItem<FlightPlan> {
  return entityMapItem('FlightPlan', id)
}
